#include "db.h"
#include"stu_info.c"
#include"grade.c"
#include"report.c"



// 初始化数据库
int init_database(UserDatabase *db) 
{
    int rc = sqlite3_open(DB_FILENAME, &db->db);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "数据库打开失败: %s\n", sqlite3_errmsg(db->db));
        return 0;
    }

    // 启用外键约束和WAL模式
    sqlite3_exec(db->db, "PRAGMA foreign_keys = ON;", NULL, NULL, NULL);
    sqlite3_exec(db->db, "PRAGMA journal_mode = WAL;", NULL, NULL, NULL);

    const char *sql = "CREATE TABLE IF NOT EXISTS users ("
                      "id TEXT PRIMARY KEY UNIQUE,"
                      "username TEXT UNIQUE NOT NULL,"
                      "password TEXT NOT NULL,"
                      "is_admin INTEGER NOT NULL DEFAULT 0,"
                      "class_name TEXT,"
                      "phone TEXT,"
                      "email TEXT)";
    
    char *err_msg = NULL;
    rc = sqlite3_exec(db->db, sql, NULL, NULL, &err_msg);
    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "表创建失败: %s\n", err_msg);
        sqlite3_free(err_msg);
        sqlite3_close(db->db);
        return 0;
    }

    // 创建成绩表
    const char *grades_sql = "CREATE TABLE IF NOT EXISTS grades ("
                             "id TEXT PRIMARY KEY,"
                             "name TEXT NOT NULL,"
                             "class TEXT NOT NULL,"
                             "chinese REAL,"
                             "math REAL,"
                             "english REAL,"
                             "physics REAL,"
                             "chemistry REAL,"
                             "biology REAL,"
                             "total REAL,"
                             "FOREIGN KEY(id) REFERENCES users(id));";
    
    rc = sqlite3_exec(db->db, grades_sql, NULL, NULL, &err_msg);
    if (rc != SQLITE_OK) 
    {
        fprintf(stderr, "创建成绩表失败: %s\n", err_msg);
        sqlite3_free(err_msg);
        // 不返回失败，继续运行
    }                         
    return 1;
}

// 加载用户（修复字段映射）
void load_users(UserDatabase *db) {
    const char *sql = "SELECT id, username, password, is_admin, "
                     "class_name, phone, email FROM users";
    sqlite3_stmt *stmt;
    int rc = sqlite3_prepare_v2(db->db, sql, -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        fprintf(stderr, "查询准备失败: %s\n", sqlite3_errmsg(db->db));
        return;
    }

    db->count = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW && db->count < MAX_USERS) {
        User *u = &db->users[db->count++];
        
        // 正确映射字段
        const unsigned char *text;
        
        // id (第0列)
        text = sqlite3_column_text(stmt, 0);
        strncpy(u->id, text ? (char*)text : "", sizeof(u->id)-1);
        u->id[sizeof(u->id)-1] = '\0';

        // username (第1列)
        text = sqlite3_column_text(stmt, 1);
        strncpy(u->username, text ? (char*)text : "", sizeof(u->username)-1);
        u->username[sizeof(u->username)-1] = '\0';
        
        // password (第2列)
        text = sqlite3_column_text(stmt, 2);
        strncpy(u->password, text ? (char*)text : "", sizeof(u->password)-1);
        u->password[sizeof(u->password)-1] = '\0';
        
        // is_admin (第3列，整数)
        u->is_admin = sqlite3_column_int(stmt, 3);
        
        // class_name (第4列)
        text = sqlite3_column_text(stmt, 4);
        if (text) {
            strncpy(u->class_name, (char*)text, sizeof(u->class_name)-1);
            u->class_name[sizeof(u->class_name)-1] = '\0';
        } else {
            u->class_name[0] = '\0';
        }
        
        // phone (第5列)
        text = sqlite3_column_text(stmt, 5);
        if (text) {
            strncpy(u->phone, (char*)text, sizeof(u->phone)-1);
            u->phone[sizeof(u->phone)-1] = '\0';
        } else {
            u->phone[0] = '\0';
        }
        
        // email (第6列)
        text = sqlite3_column_text(stmt, 6);
        if (text) {
            strncpy(u->email, (char*)text, sizeof(u->email)-1);
            u->email[sizeof(u->email)-1] = '\0';
        } else {
            u->email[0] = '\0';
        }
    }

    sqlite3_finalize(stmt);
}


// 创建初始管理员（修复：为管理员生成唯一ID）
void create_first_admin(UserDatabase *db) {
    // 检查是否已有管理员账户
    for (int i = 0; i < db->count; i++) {
        if (db->users[i].is_admin) {
            return;  // 已有管理员，不创建
        }
    }
    
    User admin = {0};
    printf("\n=== 系统首次运行，创建初始管理员账户 ===\n");
    
    printf("用户名: "); 
    scanf("%49s", admin.username);
    clear_input_buffer();
    
    printf("密码: "); 
    scanf("%49s", admin.password);
    clear_input_buffer();
    
    // 为管理员生成唯一ID (admin_用户名)
    snprintf(admin.id,64, "admin_%s", admin.username);
    admin.is_admin = 1;
    
    printf("电话: "); 
    scanf("%19s", admin.phone);
    clear_input_buffer();
    
    printf("邮箱: "); 
    scanf("%49s", admin.email);
    clear_input_buffer();
    
    strcpy(admin.class_name, "");
    
    db->users[db->count++] = admin;
    save_users(db);
    
    printf("\n管理员账户创建成功！\n用户名: %s\n密码: %s\n", admin.username, admin.password);
    printf("请妥善保管管理员账户信息！\n");
}

// 登录
int login(UserDatabase *db, char *username, char *password) 
{
    for (int i = 0; i < db->count; i++) 
    {
        if (strcmp(db->users[i].username, username) == 0 && 
            strcmp(db->users[i].password, password) == 0) {
            return i;
        }
    }
    return -1;
}

// 查看个人信息
void view_personal_info(UserDatabase *db, int index) 
{
    User *u = &db->users[index];
    
    printf("\n=== 个人信息 ===\n");
    printf("用户名: %s\n", u->username);
    printf("用户类型: %s\n", u->is_admin ? "管理员" : "学生");
    
    if (!u->is_admin) {
        printf("学号: %s\n", u->id);
        printf("班级: %s\n", u->class_name);
    }
    
    printf("电话: %s\n", u->phone);
    printf("邮箱: %s\n", u->email);
}

// 修改个人信息
void update_personal_info(UserDatabase *db, int index) {
    User *u = &db->users[index];
    
    printf("\n=== 修改个人信息 ===\n");
    printf("当前电话: %s\n新电话: ", u->phone);
    scanf("%19s", u->phone);
    clear_input_buffer();
    
    printf("当前邮箱: %s\n新邮箱: ", u->email);
    scanf("%49s", u->email);
    clear_input_buffer();
    
    save_users(db);
    printf("\n个人信息已更新！\n");
}

// 修改密码（确保数据库更新）
void change_password(UserDatabase *db, int index) {
    User *u = &db->users[index];
    char old_password[50], new_password[50];
    
    printf("\n=== 修改密码 ===\n");
    printf("当前密码: "); 
    scanf("%49s", old_password);
    clear_input_buffer();
    
    if (strcmp(old_password, u->password) != 0) {
        printf("错误：密码不正确！\n");
        return;
    }
    
    printf("新密码: "); 
    scanf("%49s", new_password);
    clear_input_buffer();
    
    printf("确认新密码: "); 
    char confirm_password[50];
    scanf("%49s", confirm_password);
    clear_input_buffer();
    
    if (strcmp(new_password, confirm_password) != 0) {
        printf("错误：两次输入的密码不一致！\n");
        return;
    }
    
    // 使用事务确保数据一致性
    sqlite3_exec(db->db, "BEGIN TRANSACTION;", NULL, NULL, NULL);
    
    const char *sql = "UPDATE users SET password = ? WHERE id = ?";
    sqlite3_stmt *stmt;
    
    int rc = sqlite3_prepare_v2(db->db, sql, -1, &stmt, NULL);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "准备更新密码失败: %s\n", sqlite3_errmsg(db->db));
        sqlite3_exec(db->db, "ROLLBACK;", NULL, NULL, NULL);
        return;
    }
    
    sqlite3_bind_text(stmt, 1, new_password, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, u->id, -1, SQLITE_STATIC);
    
    rc = sqlite3_step(stmt);
    if (rc != SQLITE_DONE) {
        fprintf(stderr, "密码更新失败: %s\n", sqlite3_errmsg(db->db));
        sqlite3_exec(db->db, "ROLLBACK;", NULL, NULL, NULL);
    } else {
        sqlite3_exec(db->db, "COMMIT;", NULL, NULL, NULL);
        // 更新内存中的密码
        strcpy(u->password, new_password);
        printf("\n密码修改成功！请妥善保管新密码\n");
    }
    
    sqlite3_finalize(stmt);
}




// 升级用户为管理员（修复数据库更新）
void promote_to_admin(UserDatabase *db) {
    char username[50];
    printf("\n请输入要升级为管理员的用户名: ");
    scanf("%49s", username);
    clear_input_buffer();
    
    int index = -1;
    for (int i = 0; i < db->count; i++) {
        if (strcmp(db->users[i].username, username) == 0 && !db->users[i].is_admin) {
            index = i;
            break;
        }
    }
    
    if (index == -1) {
        printf("错误：未找到该用户或已是管理员\n");
        return;
    }

    char confirm;
    printf("\n确定要将 %s (学号: %s) 升级为管理员吗？(y/n): ", 
           db->users[index].username, db->users[index].id);
    scanf(" %c", &confirm);
    clear_input_buffer();
    
    if (confirm == 'y' || confirm == 'Y') {
        // 开始事务
        sqlite3_exec(db->db, "BEGIN TRANSACTION;", NULL, NULL, NULL);
        
        char *err_msg = NULL;
        char sql[200];
        snprintf(sql, sizeof(sql), 
                "UPDATE users SET is_admin = 1 WHERE id = '%s';", 
                db->users[index].id);
        
        int rc = sqlite3_exec(db->db, sql, NULL, NULL, &err_msg);
        if (rc != SQLITE_OK) {
            fprintf(stderr, "升级管理员失败: %s\n", err_msg);
            sqlite3_free(err_msg);
            sqlite3_exec(db->db, "ROLLBACK;", NULL, NULL, NULL);
            return;
        }
        
        // 提交事务
        sqlite3_exec(db->db, "COMMIT;", NULL, NULL, NULL);
        
        // 更新内存中的状态
        db->users[index].is_admin = 1;
        
        printf("\n用户 %s 已升级为管理员\n", username);
    } else {
        printf("升级操作已取消\n");
    }
}
